<template>
  <div class="knowledge-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <Icon name="book-open" :size="24" />
          知识库管理
        </h1>
        <p class="page-description">管理和组织您的知识库内容</p>
      </div>

      <div class="header-right">
        <Button type="secondary" icon="upload" @click="showImportDialog = true">
          导入知识
        </Button>

        <Button type="primary" icon="plus" @click="createKnowledge">
          新建知识
        </Button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <Card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <Icon name="file-text" :size="24" class="icon-primary" />
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.totalKnowledge }}</h3>
            <p class="stat-label">总知识条目</p>
          </div>
        </div>
      </Card>

      <Card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <Icon name="folder" :size="24" class="icon-success" />
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.totalCategories }}</h3>
            <p class="stat-label">知识分类</p>
          </div>
        </div>
      </Card>

      <Card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <Icon name="database" :size="24" class="icon-warning" />
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ formatFileSize(stats.totalSize) }}</h3>
            <p class="stat-label">存储空间</p>
          </div>
        </div>
      </Card>

      <Card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <Icon name="clock" :size="24" class="icon-info" />
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.recentUpdates }}</h3>
            <p class="stat-label">近期更新</p>
          </div>
        </div>
      </Card>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-section">
          <h3 class="section-title">知识分类</h3>

          <div class="category-tree">
            <div
              v-for="category in categories"
              :key="category.id"
              class="category-item"
              :class="{ active: selectedCategory === category.id }"
              @click="selectCategory(category.id)"
            >
              <div class="category-content">
                <Icon
                  :name="category.expanded ? 'chevron-down' : 'chevron-right'"
                  :size="14"
                  class="expand-icon"
                  @click.stop="toggleCategory(category.id)"
                />
                <Icon :name="category.icon" :size="16" class="category-icon" />
                <span class="category-name">{{ category.name }}</span>
                <span class="category-count">({{ category.count }})</span>
              </div>

              <div
                v-if="category.expanded && category.children"
                class="subcategories"
              >
                <div
                  v-for="subcategory in category.children"
                  :key="subcategory.id"
                  class="subcategory-item"
                  :class="{ active: selectedCategory === subcategory.id }"
                  @click.stop="selectCategory(subcategory.id)"
                >
                  <Icon
                    :name="subcategory.icon"
                    :size="14"
                    class="subcategory-icon"
                  />
                  <span class="subcategory-name">{{ subcategory.name }}</span>
                  <span class="subcategory-count"
                    >({{ subcategory.count }})</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="sidebar-section">
          <h3 class="section-title">快速操作</h3>

          <div class="quick-actions">
            <Button
              type="text"
              icon="search"
              size="small"
              @click="focusSearch"
              class="quick-action"
            >
              搜索知识
            </Button>

            <Button
              type="text"
              icon="tag"
              size="small"
              @click="showTagManager = true"
              class="quick-action"
            >
              标签管理
            </Button>

            <Button
              type="text"
              icon="download"
              size="small"
              @click="exportKnowledge"
              class="quick-action"
            >
              导出数据
            </Button>

            <Button
              type="text"
              icon="settings"
              size="small"
              @click="showSettings = true"
              class="quick-action"
            >
              设置
            </Button>
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-area">
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="toolbar-left">
            <div class="search-box">
              <Icon name="search" :size="16" class="search-icon" />
              <input
                ref="searchInput"
                v-model="searchQuery"
                type="text"
                placeholder="搜索知识库..."
                class="search-input"
                @input="handleSearch"
              />
              <Button
                v-if="searchQuery"
                type="text"
                icon="x"
                size="small"
                @click="clearSearch"
                class="clear-search"
              />
            </div>

            <div class="filter-controls">
              <select v-model="sortBy" class="sort-select">
                <option value="updated">最近更新</option>
                <option value="created">创建时间</option>
                <option value="name">名称</option>
                <option value="size">大小</option>
              </select>

              <Button
                type="text"
                :icon="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"
                size="small"
                @click="toggleSortOrder"
                title="排序方向"
              />
            </div>
          </div>

          <div class="toolbar-right">
            <div class="view-controls">
              <Button
                type="text"
                icon="grid"
                size="small"
                :class="{ active: viewMode === 'grid' }"
                @click="viewMode = 'grid'"
                title="网格视图"
              />

              <Button
                type="text"
                icon="list"
                size="small"
                :class="{ active: viewMode === 'list' }"
                @click="viewMode = 'list'"
                title="列表视图"
              />
            </div>

            <Button
              v-if="selectedItems.length > 0"
              type="text"
              icon="trash"
              size="small"
              @click="deleteSelected"
              title="删除选中"
              class="delete-button"
            />
          </div>
        </div>

        <!-- 知识库列表 -->
        <div class="knowledge-list" :class="`view-${viewMode}`">
          <Loading v-if="loading" />

          <div v-else-if="filteredKnowledge.length === 0" class="empty-state">
            <Icon name="book-open" :size="48" class="empty-icon" />
            <h3 class="empty-title">暂无知识内容</h3>
            <p class="empty-description">
              {{
                searchQuery
                  ? "没有找到匹配的知识内容"
                  : "开始创建您的第一个知识条目"
              }}
            </p>
            <Button
              v-if="!searchQuery"
              type="primary"
              icon="plus"
              @click="createKnowledge"
            >
              创建知识
            </Button>
          </div>

          <div v-else class="knowledge-items">
            <div
              v-for="item in paginatedKnowledge"
              :key="item.id"
              class="knowledge-item"
              :class="{ selected: selectedItems.includes(item.id) }"
              @click="selectItem(item)"
            >
              <div class="item-checkbox">
                <input
                  type="checkbox"
                  :checked="selectedItems.includes(item.id)"
                  @change="toggleSelection(item.id)"
                  @click.stop
                />
              </div>

              <div class="item-icon">
                <Icon :name="getItemIcon(item.type)" :size="20" />
              </div>

              <div class="item-content">
                <h4 class="item-title">{{ item.title }}</h4>
                <p class="item-description">
                  {{ item.description || "暂无描述" }}
                </p>

                <div class="item-meta">
                  <span class="item-type">{{
                    getItemTypeLabel(item.type)
                  }}</span>
                  <span class="item-size">{{ formatFileSize(item.size) }}</span>
                  <span class="item-date">{{
                    formatDate(item.updatedAt)
                  }}</span>
                </div>

                <div v-if="item.tags && item.tags.length > 0" class="item-tags">
                  <span
                    v-for="tag in item.tags.slice(0, 3)"
                    :key="tag"
                    class="item-tag"
                  >
                    {{ tag }}
                  </span>
                  <span v-if="item.tags.length > 3" class="more-tags">
                    +{{ item.tags.length - 3 }}
                  </span>
                </div>
              </div>

              <div class="item-actions">
                <Button
                  type="text"
                  icon="edit"
                  size="small"
                  @click.stop="editKnowledge(item)"
                  title="编辑"
                />

                <Button
                  type="text"
                  icon="copy"
                  size="small"
                  @click.stop="duplicateKnowledge(item)"
                  title="复制"
                />

                <Button
                  type="text"
                  icon="more-vertical"
                  size="small"
                  @click.stop="showItemMenu(item, $event)"
                  title="更多"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination">
          <Button
            type="text"
            icon="chevron-left"
            :disabled="currentPage === 1"
            @click="currentPage--"
          />

          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>

          <Button
            type="text"
            icon="chevron-right"
            :disabled="currentPage === totalPages"
            @click="currentPage++"
          />
        </div>
      </div>
    </div>

    <!-- 知识编辑器 -->
    <KnowledgeEditor
      v-if="showEditor"
      :visible="showEditor"
      :knowledge="editingKnowledge"
      @close="closeEditor"
      @save="saveKnowledge"
    />

    <!-- 导入对话框 -->
    <Modal
      v-if="showImportDialog"
      :visible="showImportDialog"
      title="导入知识库"
      @close="showImportDialog = false"
    >
      <div class="import-dialog">
        <div class="import-options">
          <div class="import-option" @click="importFromFile">
            <Icon name="upload" :size="24" />
            <h4>从文件导入</h4>
            <p>支持 JSON、CSV、TXT 格式</p>
          </div>

          <div class="import-option" @click="importFromUrl">
            <Icon name="link" :size="24" />
            <h4>从URL导入</h4>
            <p>从网页或API导入内容</p>
          </div>

          <div class="import-option" @click="importFromClipboard">
            <Icon name="clipboard" :size="24" />
            <h4>从剪贴板导入</h4>
            <p>导入剪贴板中的文本内容</p>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 标签管理器 -->
    <Modal
      v-if="showTagManager"
      :visible="showTagManager"
      title="标签管理"
      @close="showTagManager = false"
    >
      <div class="tag-manager">
        <div class="tag-input">
          <input
            v-model="newTagName"
            type="text"
            placeholder="输入新标签名称"
            class="tag-name-input"
            @keyup.enter="createTag"
          />
          <Button
            type="primary"
            @click="createTag"
            :disabled="!newTagName.trim()"
          >
            添加
          </Button>
        </div>

        <div class="existing-tags">
          <div v-for="tag in allTags" :key="tag.id" class="tag-item">
            <span class="tag-name">{{ tag.name }}</span>
            <span class="tag-count">({{ tag.count }})</span>
            <Button
              type="text"
              icon="x"
              size="small"
              @click="deleteTag(tag.id)"
            />
          </div>
        </div>
      </div>
    </Modal>

    <!-- 项目菜单 -->
    <div
      v-if="showItemMenuFor"
      class="item-menu"
      :style="itemMenuStyle"
      v-click-outside="closeItemMenu"
    >
      <div class="menu-item" @click="viewKnowledge(showItemMenuFor)">
        <Icon name="eye" :size="14" />
        <span>查看</span>
      </div>
      <div class="menu-item" @click="editKnowledge(showItemMenuFor)">
        <Icon name="edit" :size="14" />
        <span>编辑</span>
      </div>
      <div class="menu-item" @click="duplicateKnowledge(showItemMenuFor)">
        <Icon name="copy" :size="14" />
        <span>复制</span>
      </div>
      <div class="menu-item" @click="shareKnowledge(showItemMenuFor)">
        <Icon name="share" :size="14" />
        <span>分享</span>
      </div>
      <div class="menu-divider"></div>
      <div class="menu-item danger" @click="deleteKnowledge(showItemMenuFor)">
        <Icon name="trash" :size="14" />
        <span>删除</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { useKnowledgeStore } from "@/stores/knowledge";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";
import Card from "@/components/common/Card.vue";
import Loading from "@/components/common/Loading.vue";
import Modal from "@/components/common/Modal.vue";
import KnowledgeEditor from "@/components/knowledge/KnowledgeEditor.vue";

interface KnowledgeItem {
  id: string;
  title: string;
  description?: string;
  content: string;
  type: "text" | "markdown" | "document" | "image" | "video" | "audio";
  category: string;
  tags: string[];
  size: number;
  createdAt: Date;
  updatedAt: Date;
}

interface Category {
  id: string;
  name: string;
  icon: string;
  count: number;
  expanded?: boolean;
  children?: Category[];
}

interface Tag {
  id: string;
  name: string;
  count: number;
}

interface Stats {
  totalKnowledge: number;
  totalCategories: number;
  totalSize: number;
  recentUpdates: number;
}

// Router
const router = useRouter();

// Store
const knowledgeStore = useKnowledgeStore();

// 响应式数据
const loading = ref(false);
const searchQuery = ref("");
const selectedCategory = ref("all");
const sortBy = ref("updated");
const sortOrder = ref<"asc" | "desc">("desc");
const viewMode = ref<"grid" | "list">("list");
const currentPage = ref(1);
const pageSize = ref(20);
const selectedItems = ref<string[]>([]);

// 对话框状态
const showEditor = ref(false);
const showImportDialog = ref(false);
const showTagManager = ref(false);
const showSettings = ref(false);

// 编辑相关
const editingKnowledge = ref<KnowledgeItem | null>(null);

// 标签管理
const newTagName = ref("");

// 项目菜单
const showItemMenuFor = ref<KnowledgeItem | null>(null);
const itemMenuStyle = ref({});

// 搜索输入引用
const searchInput = ref<HTMLInputElement>();

// 模拟数据
const knowledgeItems = ref<KnowledgeItem[]>([
  {
    id: "1",
    title: "Vue 3 组件开发指南",
    description: "详细介绍Vue 3组件的开发方法和最佳实践",
    content: "# Vue 3 组件开发指南\n\n...",
    type: "markdown",
    category: "frontend",
    tags: ["Vue", "前端", "组件"],
    size: 15420,
    createdAt: new Date("2024-01-15"),
    updatedAt: new Date("2024-01-20"),
  },
  {
    id: "2",
    title: "TypeScript 类型系统",
    description: "TypeScript高级类型系统的使用技巧",
    content: "TypeScript类型系统内容...",
    type: "text",
    category: "programming",
    tags: ["TypeScript", "类型系统"],
    size: 8960,
    createdAt: new Date("2024-01-10"),
    updatedAt: new Date("2024-01-18"),
  },
  {
    id: "3",
    title: "API设计规范",
    description: "RESTful API设计的最佳实践和规范",
    content: "API设计规范内容...",
    type: "document",
    category: "backend",
    tags: ["API", "REST", "规范"],
    size: 12340,
    createdAt: new Date("2024-01-08"),
    updatedAt: new Date("2024-01-16"),
  },
]);

const categories = ref<Category[]>([
  {
    id: "all",
    name: "全部",
    icon: "folder",
    count: 25,
    expanded: true,
  },
  {
    id: "frontend",
    name: "前端开发",
    icon: "monitor",
    count: 8,
    expanded: false,
    children: [
      { id: "vue", name: "Vue.js", icon: "code", count: 3 },
      { id: "react", name: "React", icon: "code", count: 2 },
      { id: "css", name: "CSS", icon: "palette", count: 3 },
    ],
  },
  {
    id: "backend",
    name: "后端开发",
    icon: "server",
    count: 6,
    expanded: false,
    children: [
      { id: "nodejs", name: "Node.js", icon: "code", count: 2 },
      { id: "python", name: "Python", icon: "code", count: 2 },
      { id: "database", name: "数据库", icon: "database", count: 2 },
    ],
  },
  {
    id: "programming",
    name: "编程语言",
    icon: "code",
    count: 7,
    expanded: false,
  },
  {
    id: "tools",
    name: "开发工具",
    icon: "tool",
    count: 4,
    expanded: false,
  },
]);

const allTags = ref<Tag[]>([
  { id: "1", name: "Vue", count: 5 },
  { id: "2", name: "前端", count: 8 },
  { id: "3", name: "TypeScript", count: 6 },
  { id: "4", name: "API", count: 4 },
  { id: "5", name: "组件", count: 7 },
]);

// 计算属性
const stats = computed<Stats>(() => ({
  totalKnowledge: knowledgeItems.value.length,
  totalCategories: categories.value.length - 1, // 排除"全部"分类
  totalSize: knowledgeItems.value.reduce((sum, item) => sum + item.size, 0),
  recentUpdates: knowledgeItems.value.filter((item) => {
    const daysDiff =
      (Date.now() - item.updatedAt.getTime()) / (1000 * 60 * 60 * 24);
    return daysDiff <= 7;
  }).length,
}));

const filteredKnowledge = computed(() => {
  let items = knowledgeItems.value;

  // 分类筛选
  if (selectedCategory.value !== "all") {
    items = items.filter((item) => item.category === selectedCategory.value);
  }

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    items = items.filter(
      (item) =>
        item.title.toLowerCase().includes(query) ||
        item.description?.toLowerCase().includes(query) ||
        item.tags.some((tag) => tag.toLowerCase().includes(query)),
    );
  }

  // 排序
  items.sort((a, b) => {
    let aValue: any, bValue: any;

    switch (sortBy.value) {
      case "name":
        aValue = a.title;
        bValue = b.title;
        break;
      case "size":
        aValue = a.size;
        bValue = b.size;
        break;
      case "created":
        aValue = a.createdAt.getTime();
        bValue = b.createdAt.getTime();
        break;
      default: // updated
        aValue = a.updatedAt.getTime();
        bValue = b.updatedAt.getTime();
    }

    if (sortOrder.value === "asc") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });

  return items;
});

const totalPages = computed(() =>
  Math.ceil(filteredKnowledge.value.length / pageSize.value),
);

const paginatedKnowledge = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredKnowledge.value.slice(start, end);
});

// 方法
const selectCategory = (categoryId: string) => {
  selectedCategory.value = categoryId;
  currentPage.value = 1;
};

const toggleCategory = (categoryId: string) => {
  const category = categories.value.find((c) => c.id === categoryId);
  if (category) {
    category.expanded = !category.expanded;
  }
};

const focusSearch = () => {
  nextTick(() => {
    searchInput.value?.focus();
  });
};

const handleSearch = () => {
  currentPage.value = 1;
};

const clearSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1;
};

const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
};

const selectItem = (item: KnowledgeItem) => {
  // 单击选择项目，可以用于预览等
  // 选择项目: item
};

const toggleSelection = (itemId: string) => {
  const index = selectedItems.value.indexOf(itemId);
  if (index > -1) {
    selectedItems.value.splice(index, 1);
  } else {
    selectedItems.value.push(itemId);
  }
};

const createKnowledge = () => {
  editingKnowledge.value = null;
  showEditor.value = true;
};

const editKnowledge = (item: KnowledgeItem) => {
  editingKnowledge.value = item;
  showEditor.value = true;
  closeItemMenu();
};

const viewKnowledge = (item: KnowledgeItem) => {
  // 查看知识详情
  router.push(`/knowledge/${item.id}`);
  closeItemMenu();
};

const duplicateKnowledge = (item: KnowledgeItem) => {
  const newItem: KnowledgeItem = {
    ...item,
    id: Date.now().toString(),
    title: `${item.title} (副本)`,
    createdAt: new Date(),
    updatedAt: new Date(),
  };

  knowledgeItems.value.unshift(newItem);
  closeItemMenu();
};

const deleteKnowledge = (item: KnowledgeItem) => {
  if (confirm(`确定要删除"${item.title}"吗？此操作不可撤销。`)) {
    const index = knowledgeItems.value.findIndex((k) => k.id === item.id);
    if (index > -1) {
      knowledgeItems.value.splice(index, 1);
    }
  }
  closeItemMenu();
};

const shareKnowledge = (item: KnowledgeItem) => {
  // 分享知识的逻辑
  // 分享知识: item
  closeItemMenu();
};

const deleteSelected = () => {
  if (selectedItems.value.length === 0) return;

  if (
    confirm(
      `确定要删除选中的 ${selectedItems.value.length} 个项目吗？此操作不可撤销。`,
    )
  ) {
    knowledgeItems.value = knowledgeItems.value.filter(
      (item) => !selectedItems.value.includes(item.id),
    );
    selectedItems.value = [];
  }
};

const closeEditor = () => {
  showEditor.value = false;
  editingKnowledge.value = null;
};

const saveKnowledge = (knowledgeData: any) => {
  if (editingKnowledge.value) {
    // 更新现有知识
    const index = knowledgeItems.value.findIndex(
      (k) => k.id === editingKnowledge.value!.id,
    );
    if (index > -1) {
      knowledgeItems.value[index] = {
        ...knowledgeItems.value[index],
        ...knowledgeData,
        updatedAt: new Date(),
      };
    }
  } else {
    // 创建新知识
    const newKnowledge: KnowledgeItem = {
      id: Date.now().toString(),
      ...knowledgeData,
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    knowledgeItems.value.unshift(newKnowledge);
  }

  closeEditor();
};

const showItemMenu = (item: KnowledgeItem, event: MouseEvent) => {
  showItemMenuFor.value = item;

  const rect = (event.target as HTMLElement).getBoundingClientRect();
  itemMenuStyle.value = {
    position: "fixed",
    top: `${rect.bottom + 5}px`,
    left: `${rect.left}px`,
    zIndex: 1000,
  };
};

const closeItemMenu = () => {
  showItemMenuFor.value = null;
};

const importFromFile = () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".json,.csv,.txt";
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) {
      // 处理文件导入
      // 导入文件: file
    }
  };
  input.click();
  showImportDialog.value = false;
};

const importFromUrl = () => {
  const url = prompt("请输入要导入的URL:");
  if (url) {
    // 处理URL导入
    // 导入URL: url
  }
  showImportDialog.value = false;
};

const importFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText();
    if (text) {
      // 处理剪贴板导入
      // 导入剪贴板内容: text
    }
  } catch {
    // 读取剪贴板失败
  }
  showImportDialog.value = false;
};

const exportKnowledge = () => {
  const data = {
    knowledge: knowledgeItems.value,
    categories: categories.value,
    tags: allTags.value,
    exportTime: new Date().toISOString(),
  };

  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `knowledge-export-${Date.now()}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const createTag = () => {
  if (!newTagName.value.trim()) return;

  const newTag: Tag = {
    id: Date.now().toString(),
    name: newTagName.value.trim(),
    count: 0,
  };

  allTags.value.push(newTag);
  newTagName.value = "";
};

const deleteTag = (tagId: string) => {
  const index = allTags.value.findIndex((t) => t.id === tagId);
  if (index > -1) {
    allTags.value.splice(index, 1);
  }
};

const getItemIcon = (type: string): string => {
  const icons = {
    text: "file-text",
    markdown: "file-text",
    document: "file",
    image: "image",
    video: "video",
    audio: "music",
  };
  return icons[type as keyof typeof icons] || "file";
};

const getItemTypeLabel = (type: string): string => {
  const labels = {
    text: "文本",
    markdown: "Markdown",
    document: "文档",
    image: "图片",
    video: "视频",
    audio: "音频",
  };
  return labels[type as keyof typeof labels] || "未知";
};

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
};

const formatDate = (date: Date): string => {
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    return "今天";
  } else if (days === 1) {
    return "昨天";
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 生命周期
onMounted(() => {
  // 初始化数据
});

// 点击外部关闭菜单的指令
const vClickOutside = {
  mounted(el: HTMLElement, binding: any) {
    el.clickOutsideEvent = (event: Event) => {
      if (!(el === event.target || el.contains(event.target as Node))) {
        binding.value();
      }
    };
    document.addEventListener("click", el.clickOutsideEvent);
  },
  unmounted(el: HTMLElement) {
    document.removeEventListener("click", el.clickOutsideEvent);
  },
};
</script>

<style scoped>
/* 页面基础样式 */
.knowledge-page {
  padding: 24px;
  background-color: var(--bg-primary);
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px;
}

.page-description {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0;
}

.header-right {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  padding: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-primary {
  background-color: var(--primary-color-light);
  color: var(--primary-color);
}

.icon-success {
  background-color: var(--success-color-light);
  color: var(--success-color);
}

.icon-warning {
  background-color: var(--warning-color-light);
  color: var(--warning-color);
}

.icon-info {
  background-color: var(--info-color-light);
  color: var(--info-color);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

/* 主要内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 24px;
}

/* 侧边栏 */
.sidebar {
  background-color: var(--bg-secondary);
  border-radius: 12px;
  padding: 20px;
  height: fit-content;
}

.sidebar-section {
  margin-bottom: 32px;
}

.sidebar-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px;
}

/* 分类树 */
.category-tree {
  space-y: 4px;
}

.category-item {
  border-radius: 8px;
  transition: all 0.2s ease;
  cursor: pointer;
}

.category-item:hover {
  background-color: var(--bg-tertiary);
}

.category-item.active {
  background-color: var(--primary-color-light);
  color: var(--primary-color);
}

.category-content {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  font-size: 14px;
}

.expand-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.category-icon {
  color: var(--text-secondary);
}

.category-name {
  flex: 1;
  font-weight: 500;
}

.category-count {
  font-size: 12px;
  color: var(--text-tertiary);
}

.subcategories {
  margin-left: 20px;
  margin-top: 4px;
}

.subcategory-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.subcategory-item:hover {
  background-color: var(--bg-tertiary);
}

.subcategory-item.active {
  background-color: var(--primary-color-light);
  color: var(--primary-color);
}

.subcategory-icon {
  color: var(--text-tertiary);
}

.subcategory-name {
  flex: 1;
}

.subcategory-count {
  font-size: 11px;
  color: var(--text-tertiary);
}

/* 快速操作 */
.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.quick-action {
  justify-content: flex-start;
  padding: 8px 12px;
  font-size: 14px;
}

/* 内容区域 */
.content-area {
  background-color: var(--bg-secondary);
  border-radius: 12px;
  padding: 24px;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-tertiary);
}

.search-input {
  width: 100%;
  padding: 10px 12px 10px 40px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
  transition: all 0.2s ease;
}

.search-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px var(--primary-color-light);
}

.clear-search {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-select {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
}

.sort-select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.view-controls {
  display: flex;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
}

.view-controls .btn {
  border-radius: 0;
  border: none;
}

.view-controls .btn.active {
  background-color: var(--primary-color);
  color: white;
}

.delete-button {
  color: var(--error-color);
}

/* 知识库列表 */
.knowledge-list {
  min-height: 400px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  color: var(--text-tertiary);
  margin-bottom: 16px;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px;
}

.empty-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0 0 24px;
}

/* 知识项目 */
.knowledge-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.view-grid .knowledge-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.knowledge-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background-color: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.knowledge-item:hover {
  border-color: var(--primary-color-light);
  box-shadow: var(--shadow-sm);
}

.knowledge-item.selected {
  border-color: var(--primary-color);
  background-color: var(--primary-color-light);
}

.view-grid .knowledge-item {
  flex-direction: column;
  align-items: flex-start;
  text-align: left;
}

.item-checkbox {
  flex-shrink: 0;
}

.item-checkbox input {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.item-icon {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  background-color: var(--bg-tertiary);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
}

.view-grid .item-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 12px;
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.view-grid .item-title {
  white-space: normal;
  line-height: 1.4;
}

.item-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0 0 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.view-grid .item-description {
  white-space: normal;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: var(--text-tertiary);
  margin-bottom: 8px;
}

.item-tags {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.item-tag {
  padding: 2px 6px;
  background-color: var(--bg-tertiary);
  border-radius: 4px;
  font-size: 11px;
  color: var(--text-secondary);
}

.more-tags {
  font-size: 11px;
  color: var(--text-tertiary);
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.knowledge-item:hover .item-actions {
  opacity: 1;
}

.view-grid .item-actions {
  align-self: flex-end;
  margin-top: auto;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--border-color);
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 导入对话框 */
.import-dialog {
  padding: 20px 0;
}

.import-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.import-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px;
  background-color: var(--bg-tertiary);
  border: 2px solid var(--border-color);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
}

.import-option:hover {
  border-color: var(--primary-color);
  background-color: var(--primary-color-light);
}

.import-option h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 12px 0 4px;
}

.import-option p {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

/* 标签管理器 */
.tag-manager {
  padding: 20px 0;
}

.tag-input {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.tag-name-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
}

.tag-name-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.existing-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background-color: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  font-size: 14px;
}

.tag-name {
  color: var(--text-primary);
}

.tag-count {
  color: var(--text-tertiary);
  font-size: 12px;
}

/* 项目菜单 */
.item-menu {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: var(--shadow-lg);
  min-width: 150px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: var(--text-primary);
}

.menu-item:hover {
  background-color: var(--bg-tertiary);
}

.menu-item.danger {
  color: var(--error-color);
}

.menu-item.danger:hover {
  background-color: var(--error-color-light);
}

.menu-divider {
  height: 1px;
  background-color: var(--border-color);
  margin: 4px 0;
}

/* 响应式 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 240px 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .knowledge-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .main-content {
    grid-template-columns: 1fr;
  }

  .sidebar {
    order: 2;
  }

  .content-area {
    order: 1;
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .toolbar-left {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    max-width: none;
  }
}

@media (max-width: 480px) {
  .knowledge-page {
    padding: 12px;
  }

  .page-title {
    font-size: 24px;
  }

  .header-right {
    flex-direction: column;
    gap: 8px;
  }

  .view-grid .knowledge-items {
    grid-template-columns: 1fr;
  }

  .import-options {
    grid-template-columns: 1fr;
  }
}
</style>
